package com.example.h2o.phonesearchdemo1008;

import androidx.appcompat.app.AppCompatActivity;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.example.h2o.phonesearchdemo1008.bean.VResponse;
import com.google.gson.Gson;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {
    Button btSend;
    EditText etPhone;
    TextView tvShow;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btSend = findViewById(R.id.bt_send);
        etPhone = findViewById(R.id.et_phone);
        tvShow = findViewById(R.id.tv_show);
        btSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sendPhone();
            }
        });
    }
    private  void setTextView(final String province,final String city,final String company){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                String str = province + city + company;
                tvShow.setText(str); //启动线程更新ui
            }
        });
    }
    private void sendPhone(){
        /**
         * 网络耗时操作，需要使用线程
         */
        new Thread(new Runnable() {
            @Override
            public void run() {
                String phoneString  =etPhone.getText().toString();
                OkHttpClient okHttpClient =  new OkHttpClient();
                /**
                 * 构建请求头
                 */
                Request request = new Request.Builder().url("https://apis.juhe" +
                        ".cn/mobile/get?phone="+phoneString+"&dtype=&key" +
                        "=a3eaf52975c81e6156b4d28abe3e638c").get().build();
                /**
                 * 设置请求
                 */
                Call call = okHttpClient.newCall(request);
                try {

                    Response response = call.execute();//获取请求后返回的值
                    /**
                     * 解析json，将json转成实例化的bean类
                     */
                    Gson gson = new Gson();
                    VResponse vResponse = gson.fromJson(response.body().string(),VResponse.class);
                    Log.e("bean",vResponse.getResult().getProvince()+vResponse.getResult().getCity()+vResponse.getResult().getCompany());
                    //Log.e("okhttp",response.body().string());
                    setTextView(vResponse.getResult().getProvince(),vResponse.getResult().getCity(),vResponse.getResult().getCompany());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
